﻿#include "ChromatogramManager.h"

ChromatogramManager::ChromatogramManager(){
    _timer_tick = new QTimer(this);
    _timer_collect = new QTimer(this);
    connect(_timer_tick, SIGNAL(timeout()), this, SLOT(refresh()));
    connect(_timer_collect, SIGNAL(timeout()), this, SLOT(onCollectStop()));
}


void ChromatogramManager::onStartExperiment(){
    onEndExperiment();
    _timer_tick->start(1000);
    _chart->clear();
    _chart->setFixedMaxX(1000);
    _chart->setFixedMaxY(800);
}

void ChromatogramManager::onCollectStop(){
    QTimer::singleShot(_delayTimeStop*1000, [=](){
        emit sigEndCollect();
        _timer_collect->stop();
    });
}


void ChromatogramManager::setDetectMode(int isAuto, int autoType, int thr, int delayTimeCollect, int timeCollect, int delayTimeStop){
    _isAuto = isAuto;
    _autoType = autoType;
    _threshold = thr;
    _delayTimeCollect = delayTimeCollect;
    _timeCollect = timeCollect;
    _delayTimeStop = delayTimeStop;
}
void ChromatogramManager::setDetectMode(int isAuto){
    _isAuto = isAuto;
}


void ChromatogramManager::setThreshold(int thr){
    qDebug() << "阈值线变更为" << thr;
    _threshold = thr;
}

QVariantMap ChromatogramManager::getDetectMode(){
    QVariantMap res;
    res["IsAuto"] = _isAuto;
    res["AutoType"] = _autoType;
    res["Threshold"] = _threshold;
    res["DelayTimeCollect"] = _delayTimeCollect;
    res["TimeCollect"] = _timeCollect;
    res["DelayTimeStop"] = _delayTimeStop;
    return res;
}


void ChromatogramManager::judgeCollectState(){

    if(_hasCollect){
        if(_autoType == 2){
            if(judgeCollectCloseStateByThr()){
                onCollectStop();
            }
        }else{
            return;
        }
    }
    // 阈值
    if(_autoType == 0){
        if(judgeCollectStateByThr()){
            emit sigStartCollect();
            _hasCollect = true;
            _timer_collect->start(_timeCollect*1000);
        }
    }else if(_autoType == 1){
        if(judgeCollectStateByPeak()){
            qDebug() << "判断Peak返回true";
            emit sigStartCollect();
            _hasCollect = true;
            _timer_collect->start(_timeCollect*1000);
        }
    }else if(_autoType == 2){
        if(judgeCollectStateByThr()){

            emit sigStartCollect();
            _hasCollect = true;
        }
    }

}

bool ChromatogramManager::judgeCollectStateByPeak(){
    qDebug() << "判断Peak" << "HasRise" << _hasRise;
    // 判断条件: (1)存在上升期 (2)当前阶段斜率达到0
    double riseSlopeThr = 3;
    double planeSlopeThr = 0.5;
    int N = 15;
    double k, b;
    if(_pointList_filter.size() < N){
        return false;
    }
    Algorithm::linearFitting(_pointList_filter.mid(std::max(0, _pointList_filter.size()-N), N), &k, &b);
    qDebug() << "当前斜率" << k;

    // 上升期判断
    if(!_hasRise){
        if(k > riseSlopeThr){
            _hasRise = true;
        }
        return false;
    }
    // 判断是否到平滑期
    else{
        if(k < planeSlopeThr){
            return true;
        }
        return false;
    }

}
bool ChromatogramManager::judgeCollectStateByThr(){
    // 判断条件: 持续N个点的值大于阈值线
    int N = 5;
    for(int i = _pointList_filter.size() - 1; i >= std::max(_pointList_filter.size() - N, 0); i --){
        if(_pointList_filter[i].y() < _threshold){
            return false;
        }
    }
    return true;
}

bool ChromatogramManager::judgeCollectCloseStateByThr(){
    // 判断条件: 持续N个点的值小于阈值线
    int N = 5;
    for(int i = _pointList_filter.size() - 1; i >= std::max(_pointList_filter.size() - N, 0); i --){
        if(_pointList_filter[i].y() < _threshold){
            return false;
        }
    }
    return true;
}

void ChromatogramManager::onEndExperiment(){
    _timer_tick->stop();
    _timer_collect->stop();
    _hasRise = false;
    _hasCollect = false;
    _pointList_raw.clear();
    _pointList_filter.clear();
}


void ChromatogramManager::refresh(){

    refreshPointList();
    judgeCollectState();

}


// 每秒刷新数据
void ChromatogramManager::refreshPointList(){



        // 嗯，编数据吧
//      for(int i = 0; i < 1; i ++){
//          int x = _pointList_raw.length();
//          _pointList_raw.append(QPointF(x, 10 + qrand()%10 + 500/(1+pow(2.7, (500.0-x)/20.0))));
//      }

    // 从下位机获取数据
    QVector<double> dataList = _msgInterface->getCPSData();
    double value = 0;
    for(int i = 0; i < dataList.size(); ++i){     // 对发过来的数据取平均作为单个点的数据
        value += dataList[i];
    }if(dataList.size()!=0){
        value /= dataList.size();
    }
    _pointList_raw.append(QPointF(_pointList_raw.size(), value));

    _chart->setFixedMaxX(std::max(600.0, std::ceil(_pointList_raw.size()/60.0)*60));
    _pointList_filter = Algorithm::filter(_pointList_raw);      // 滤波后数据
    _chart->clear();
//    _chart->appendCurve("1raw", _pointList_raw, QColor(188, 210, 233, 100), 2);



    _chart->appendCurve("2filter", _pointList_filter, QColor(233, 133, 12), 2);
    _chart->refresh();
}



